package com.xyh.flowershop.intercepts;

import com.alibaba.druid.util.StringUtils;
import com.xyh.flowershop.cache.RedisCache;
import com.xyh.flowershop.constant.CacheConstant;
import com.xyh.flowershop.constant.CommonConstant;
import com.xyh.flowershop.context.WebContext;
import com.xyh.flowershop.exceptions.custom.AuthException;
import com.xyh.flowershop.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Objects;

/**
 * 认证拦截器，不引入SpringSecurity
 * @author 小约翰可汗
 * @className AuthIntercept
 * @createTime 2024/4/2919:29
 */
@Slf4j
@Component
public class AuthIntercept implements HandlerInterceptor {

    private final RedisCache redisCache;

    public AuthIntercept(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {

        String token = request.getHeader(CommonConstant.TOKEN_KEY);
        log.info("url:{}",request.getRequestURI());
        if(StringUtils.isEmpty(token)){
            throw new AuthException(CommonConstant.FORBIDDEN);
        }
        // 解析token,先验证这个token存不存在redis中，并验证token
        Claims claims = null;
        try {
            claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            throw new AuthException(CommonConstant.UNAUTHORIZED);
        }
        String userId = new String(claims.getSubject().getBytes(StandardCharsets.UTF_8));
        String redisVal = redisCache.getCacheObject(CacheConstant.LOGIN_PREFIX+userId);
        if(Objects.isNull(redisVal) || !token.equals(redisVal)){
            throw new AuthException(CommonConstant.UNAUTHORIZED);
        }
        WebContext.save(userId);
        log.info("当前线程{}",Thread.currentThread().getId());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    // 最后清楚threadlocal
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WebContext.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
